/**
 * Created by Administrator on 2017/11/1.
 */
//页面初始化
Param.initPageParam();
var storage = window.sessionStorage;
//根据就诊记录获取待收费处方号和检查号
var recipeAndexamineIds;
ajaxNormalPost("/chg/charges_info/getRecipeIdAndExaMineId", {
    "visiteId": getUserId()
}, function (data) {
    recipeAndexamineIds = data.data;
});

//全部处方检查号
var allChargeRecipeIds = recipeAndexamineIds.recipeIds + "";
var allChargeExamineIds = recipeAndexamineIds.examineIds + "";

storage.setItem("chargeRecipeIds", allChargeRecipeIds);
storage.setItem("chargeExamineIds", allChargeExamineIds);
storage.setItem("visiteId", getUserId());
/***********快速检索非处方对象属性定义 starting***********/
var expand_setting = {
    attribute: {"data-item-id": "id"},//放着要存在tr标签中的数据 key表示的是a标签中的属性  value表示的是json数据中的key
    param: {pageSize: 10},//url请求参数
    url: concatToken(Param.host_url + "/chg/charges_info/select_drug_srm_page"),
    method: "post",
    width: "700",//设置表格的宽度，不设置就不加
    paging: {
        pageNum: "pageNum",//表示这是第几页，后面的value表示的是服务器需要的key
        pageSize: "pageSize",//表示每页显示，后面的value表示的是服务器需要的key
        pageTotal: "pageTotal"//表示总页数，后面的value表示的是服务器需要的key
    },
    name: "search_chinaSpell",
    column: [
        {
            colspan: 6,
            text: "drgAndExaName",
            title: "药品/检查名称"
        },
        {
            colspan: 7,
            text: "drgRegionName",
            title: "药品产地名称"
        }
    ],
    rowClick: function ($tr, rowData, $input) {	//选中药品数据事件
        //当前焦点所在行
        var $inputtr = $input.parents("tr:first");
        //类型
        log4j.info(rowData);
        $inputtr.find("input[name=type]").val(rowData.type);
        $inputtr.find("input[name=state]").val(rowData.state);
        $inputtr.find("input[name=hospitalId]").val(rowData.hospitalId);
        $inputtr.find("input[name=rcpStoreId]").val(rowData.rcpStoreId);
        $inputtr.find("input[name=modId]").val(rowData.modId);
        $inputtr.find("input[name=catName]").val(rowData.catName);
        $inputtr.find("input[name=catCode]").val(rowData.catCode);
        //药品名称
        $inputtr.find("input[name=drgAndExaName]").val(rowData.drgAndExaName);
        /**规格*/
        $inputtr.find("input[name=speId]").val(rowData.speId);
        //$inputtr.find("td[colName=drgSpecification]").html(rowData.drgSpecification);
        //给药方式
        $inputtr.find("select[name=modName]").val(rowData.modId);
        //频次
        $inputtr.find("select[name=freEnName]").val(rowData.freEnName);
        //产地
        $inputtr.find("input[name=manIds]").val(rowData.manId);
        //价格
        $inputtr.find("input[name=price]").val(rowData.price);
        /***单次剂量单位获取 starting**/
        var units = [];
        if (rowData.minUnit != "" && rowData.minUnit != null) {
            units.push({unit: rowData.minUnit, value: ""});
        }
        if (rowData.doseUnit != "" && rowData.doseUnit != null) {
            units.push({unit: rowData.doseUnit, value: rowData.drgDose});
        }
        if (rowData.volumeUnit != "" && rowData.volumeUnit != null) {
            units.push({unit: rowData.volumeUnit, value: rowData.volume});
        }

        var unitHtml = '<select name="treDoseUnit">';
        $(units).each(function (index, item) {
            unitHtml += '<option value=' + item.unit + ' dose="' + item.value + '">' + item.unit + '</option>';
        });
        unitHtml += '</select>';
        //单次剂量单位html插入
        $inputtr.find("select[name=treDoseUnit]").parent().html(unitHtml);

        //包装单位
        $inputtr.find("input[name=drgPackingUnit]").val(rowData.drgPackingUnit);
        //单次剂量值
        var treOnceDose = $inputtr.find("select[name=treDoseUnit]").find("option:selected").attr("dose");
        $inputtr.find("input[name=treOnceDose]").val(treOnceDose);
        //给剂量单位绑定onchange事件，修改单位剂量
        $inputtr.find("select[name=treDoseUnit]").on("change", function () {
            treOnceDose = $inputtr.find("select[name=treDoseUnit]").find("option:selected").attr("dose");
            $inputtr.find("input[name=treOnceDose]").val(treOnceDose);
        });
        /***单次剂量单位获取 ending**/

        //给给药方式绑定onchange事件，修改分组序号
        modIdChangeEvent($inputtr);
        /**处方序号重新计算**/
        initTreNum();
        /**明细删除事件绑定*/
        bindDetailIconDelEvent();
        //回车事件绑定
        keydownEvent(initRowTemplate());

    }//单击行的事件,$tr表示单击的那行的
};
/***********快速检索对象属性定义 ending***********/
function init() {
    //给药方式
    // var usage_mode_data;
    ajaxNormalPost("/drug/usage_mode/select_list", {}, function (data) {
        // usage_mode_data = data.data;
        storage.setItem('usage_mode_data', JSON.stringify(data.data));
    }, false);

    //频次
    // var frequency_data;
    ajaxNormalPost("/drug/frequency/select_list", {}, function (data) {
        // frequency_data = data.data;
        storage.setItem('frequency_data', JSON.stringify(data.data));
    }, false);
    baseInfo();//基本信息
    createTable();//创建主表格
    createOTC();//创建非处方

}
init();
//获取非处方单的钱
function getnotNomalMoney() {
    var arrayRecipeDetail = [];
    $("#table-data-right").find("tbody").find("tr").each(function () {
        var recipeAndExamineInfo = new Object();
        recipeAndExamineInfo.speId = $(this).find("input[name=speId]").val();
        log4j.info(recipeAndExamineInfo.speId);
        recipeAndExamineInfo.state = $(this).find("input[name=state]").val();//类别
        recipeAndExamineInfo.manId = $(this).find("input[name=manIds]").val();
        log4j.info(recipeAndExamineInfo.manId);
        recipeAndExamineInfo.hospitalId = $(this).find("input[name=hospitalId]").val();//医院名称
        recipeAndExamineInfo.rcpStoreId = $(this).find("input[name=rcpStoreId]").val();//药房序号
        recipeAndExamineInfo.modId = $(this).find("input[name=modId]").val();//药房序号
        log4j.info(recipeAndExamineInfo.rcpStoreId);
        recipeAndExamineInfo.rcpPosts = $(this).find("input[name=rcpPosts]").val();//贴数
        recipeAndExamineInfo.redUseDay = $(this).find("input[name=redUseDay]").val();//用药天数
        recipeAndExamineInfo.freEnName = $(this).find("input[name=freEnName]").val();//频次
        recipeAndExamineInfo.modName = $(this).find("input[name=modName]").val();//给药方式
        recipeAndExamineInfo.catCode = $(this).find("input[name=catCode]").val();//药品类别
        recipeAndExamineInfo.price = $(this).find("input[name=price]").val();//单价
        recipeAndExamineInfo.drgAndExaName = $(this).find("input[name=drgAndExaName]").val();//名称
        recipeAndExamineInfo.quantity = $(this).find("input[name=quantity]").val();//数量
        recipeAndExamineInfo.drgPackingUnit = $(this).find("input[name=drgPackingUnit]").val();//单位
        if (recipeAndExamineInfo.drgAndExaName !== null && recipeAndExamineInfo.drgAndExaName !== undefined && recipeAndExamineInfo.drgAndExaName !== '') {
            arrayRecipeDetail.push(recipeAndExamineInfo);
        }
    });


    var price = 0;
    log4j.info(arrayRecipeDetail);//非处方信息
    var recipeAndExamineInfoes = JSON.stringify(arrayRecipeDetail);
    storage.setItem("recipeAndExamineInfoes", recipeAndExamineInfoes);

    $.ajax({
        async: false,
        type: "POST",
        //dataType : "json",
        contentType: "application/json",
        url: concatToken(Param.host_url + "/chg/charges_info/getNotNomalMoney"),
        data: recipeAndExamineInfoes,
        success: function (data, textStatus) {
            log4j.info(data);
            price = data.data.notNomalSumPrice;
            storage.setItem("notNomalSumPrice", data.data.notNomalSumPrice);
        },
        error: function (jqXHR) {
            layer.msg("请求出现例外:" + jqXHR.statusText);
            return false;
        }
    });

    return price;//返回非处方药的总钱
}
//患者基本信息
function baseInfo() {

    ajaxNormalPost('/chg/charges_info/geVisitedInfoWrapper', {visiteId: getUserId()}, function (res) {
        if (res) {
            $('#patName').text(res.data.patName || '');
            $('#patCardNum').text(res.data.patCardNum || '');
            $('#patSex').text(res.data.patSex == 1 ? '男' : '女');
            $('#patAge').text(res.data.patAge == undefined ? '' : res.data.patAge);
            $('#patContacts').text(res.data.patContacts || '');
            $('#feeName').text(res.data.feeName || '');
            $('#sffName').text(res.data.sffName || '');
            $('#depName').text(res.data.depName || '');
            $('#disTypeName').text(res.data.disTypeName || '');
            $('#patAddress').text(res.data.patAddress || '');
            $('#disName').text(res.data.disName || '');
            $('#usrNum').text('当前发票号码:' + (res.data.usrNum || ''));
            storage.setItem("sffId", res.data.sffId);
        }
    })
}
//获取用户Id
function getUserId() {
    var userId = location.search;
    if (userId) {
        return userId.split('=')[1];
    } else {
        return '';
    }
}
//创建表格
function createTable() {

    ajaxNormalPost('/chg/charges_info/getRecipeIdAndExaMineId', {visiteId: getUserId()}, function (res) {
        if (res) {
            ajaxNormalPost('/chg/charges_info/getRecipesAndExaMines', {
                recipeIds: res.data.recipeIds.join(','),
                examineIds: res.data.examineIds.join(',')
            }, function (res) {
                if (res) {
                    if (res.data.ZY.length) {//中药
                        for (var i = 0; i < res.data.ZY.length; i++) {
                            createCN(res.data.ZY[i])
                        }
                    }
                    if (res.data.XY.length) {//西药
                        for (var i = 0; i < res.data.XY.length; i++) {
                            createWt(res.data.XY[i]);
                        }
                    }
                    if (res.data.JC.length) {
                        for (var i = 0; i < res.data.JC.length; i++) {//检查
                            createJJ(res.data.JC[i], '检查开单');
                        }
                    }
                    if (res.data.JY.length) {
                        for (var i = 0; i < res.data.JY.length; i++) {//检验
                            createJJ(res.data.JY[i], '检验开单');
                        }
                    }
                    if (res.data.XM.length) {
                        for (var i = 0; i < res.data.XM.length; i++) {//收费项
                            createFee(res.data.XM[i]);
                        }
                    }
                }
            })
        }
    })
}
//创建非处方药品
function createOTC() {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center">' +
        '<span>非处方药</span>' +
        '<i class="iconfont icon-xinzeng pull-right mr20" style="font-size:25px;color:#ccc" onclick="addRow()"></i>' +
        '</h4>' +
        '<table class="table table-fixed table-hover text-center" id="table-data-right">' +
        '<thead><tr>' +
        '<td colspan="1">序号</td>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">药品名称</td>' +
        '<td colspan="4">频次</td>' +
        '<td colspan="4">给药方式</td>' +
        '<td colspan="3">天数</td>' +
        '<td colspan="3">贴数</td>' +
        '<td colspan="3">数量</td>' +
        '<td colspan="3">单位</td>' +
        ' <td colspan="3">单价(元)</td>' +
        '<td colspan="2">操作</td>' +
        '</tr></thead>' +
        '<tbody>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);
}
//增加非处方行
function addRow(frequency_data, usage_mode_data) {
    var row = initRowTemplate();
    //设置处方类别
    // $.extend(expand_setting.param, {"search_recipeType": $("#treType").val()});
    $("#table-data-right").find("tbody").append(row);
    $("#table-data-right").find("tbody").find("tr:last").find("input[name=drgAndExaName]").grayExpandTable(expand_setting);
    $("#table-data-right").find("tbody").find("tr:last").find("input[name=quantity]").on("input propertychange", function () {
        var prices = 0;
        $("#table-data-right").find("tbody").find("tr").each(function () {
            var quantity = Number($(this).find("input[name=quantity]").val().trim());
            var price = Number($(this).find("input[name=price]").val().trim());
            if (quantity === quantity && price === price) {
                prices += (quantity * price);
            }
        });
        $("#totalPrice_west").html(Math.floor(prices * 100) / 100);
    })
    /**处方序号重新计算**/
    initTreNum();
    // /**明细删除事件绑定*/
    bindDetailIconDelEvent();
    //
    keydownEvent(row);
}
/**非处方明细模板行定义**/
var self_row_index = 0;
function initRowTemplate() {
    //非处方明细行模板定义 starting
    var row = '<tr data-id="1"><input type="hidden" name="treId"><input type="hidden" name="state"><input type="hidden" name="modId">'
        + '<input type="hidden" name="treNum"><input type="hidden" name="speId"><input type="hidden" name="hospitalId">'
        + '<input type="hidden" name="manIds"><input type="hidden" name="treGroupNum"><input type="hidden" name="rcpStoreId">'
        + '<input type="hidden" name="catCode">'
        + '<td colspan="1" colName="treNum"></td>'
        + '<td colspan="2" colName="catName"><input type="text" name="catName" disabled="true"></td>'
        + '<td colspan="5" colName="drgAndExaName"><input type="text" name="drgAndExaName"></td>'
        //+ '<td colspan="3" colName="onceDose"><input type="text" name="onceDose"></td>'
        + '<td colspan="4" colName="freEnName"><select name="freEnName">';
    var frequency_data = JSON.parse(storage.getItem('frequency_data'));
    $(frequency_data).each(function (index, item) {
        row += '<option value=' + item.freEnName + '>' + item.freName + '</option>';
    });
    row += '</select></td>';
    row += '<td colspan="4" colName="modName"><select name="modName">';

    var usage_mode_data = JSON.parse(storage.getItem('usage_mode_data'));
    $(usage_mode_data).each(function (index, item) {
        row += '<option value=' + item.id + '>' + item.modName + '</option>';
    });
    row += '</select></td>';

    row += '<td colspan="3" colName="redUseDay"><input type="text" name="redUseDay"></td>'
        + '<td colspan="3" colName="rcpPosts"><input type="text" name="rcpPosts"></td>'//贴数
        + '<td colspan="3" colName="quantity"><input type="text" name="quantity"></td>'//数量
        //+ '<td colspan="3" colName="treDoseUnit"><select name="treDoseUnit"></select></td>'
        + '<td colspan="3" colName="drgPackingUnit"><input type="text" name="drgPackingUnit"></td>'
        + '<td colspan="3" colName="price"><input type="text" name="price"></td>';//单价
    row += '<td colspan="2"><i class="iconfont icon-shanchu detail-icon-del"></i></td></tr>';
    //协定处方明细行模板定义 ending
    return row;
}
/**给药方式绑定onchange事件，修改分组序号**/
function modIdChangeEvent($tr) {
    $tr.find("select[name=modId]").on("change", function () {
        var modId = $tr.find("select[name=modId]").val();
        //副药
        if (modId == 99) {
            if ($tr.find("td[colName=treNum]").text() == 1) {
                alert("请先添加主药!");
                return;
            }
            var pre_treGroupNum = $tr.prev().find("td[colName=treGroupNum]").text();
            $tr.find("td[colName=treGroupNum]").html(pre_treGroupNum);
            $tr.find("input[name=treGroupNum]").val(pre_treGroupNum);
        } else {
            $tr.find("td[colName=treGroupNum]").html($tr.find("td[colName=treNum]").text());
            $tr.find("input[name=treGroupNum]").val($tr.find("td[colName=treNum]").text());
        }
    });
}
/**分组序号重新计算**/
function initTreGroupNum() {
    $trs = $("#table-data-right").find("tbody").find("tr");
    $.each($trs, function (index, tr) {
        var modId = $(tr).find("select[name=modId]").val();
        //副药
        if (modId == 99) {
            $(tr).find("td[colName=treGroupNum]").html(index);
            $(tr).find("input[name=treGroupNum]").val(index);
            $("#totalCount_drugs").html(index);
        } else {
            $(tr).find("td[colName=treGroupNum]").html(index + 1);
            $(tr).find("input[name=treGroupNum]").val(index + 1);
            $("#totalCount_drugs").html(index + 1);
        }
    });
}
/**处方序号重新计算**/
function initTreNum() {
    $trs = $("#table-data-right").find("tbody").find("tr");
    $.each($trs, function (index, tr) {
        //添加处方序号
        $(tr).find("td[colName=treNum]").html(index + 1);
        $(tr).find("input[name=treNum]").val(index + 1);
        $("#totalCount_drugs").html(index + 1);
        //添加data-id属性
        $(tr).attr("data-id", index + 1);
    });
    //最后一行分组序号设置
    var $treGroupNum = $("#table-data-right").find("tbody").find("tr:last").find("td[colName=treGroupNum]");
    $treGroupNum.html($trs.length);
    //log4j.info($treGroupNum.html()+"总计");
}
/**明细删除事件绑定*/
function bindDetailIconDelEvent() {
    $(".detail-icon-del").off("click");

    $(".detail-icon-del").on("click", function () {
        var $tr = $(this).parents("tr");
        /*var $prev_tr = $(this).parents("tr").prev();

         var treGroupNum = $tr.find("td[colName=treGroupNum]").text();
         var prev_treGroupNum = $prev_tr.find("td[colName=treGroupNum]").text();

         if (treGroupNum != prev_treGroupNum) {
         //删除所有分组需要相同的副药
         $next_tr_all = $(this).parents("tr").nextAll();
         $.each($next_tr_all, function(index, item){
         if ($(item).find("td[colName=treGroupNum]").text() == treGroupNum) {
         $(item).remove();
         }
         });

         //删除当前行
         $tr.remove();
         } */

        $tr.remove();
        /**处方序号重新计算**/
        initTreNum();
        /**分组序号重新计算**/
        initTreGroupNum();
    });
}
//定义回车事件处理方法
function keydownEvent(row) {
    var $nbp = $("#table-data-right input:text, #table-data-right select");
    $nbp.on("keydown", function (e) {
        var key = e.which;
        if (key == 13) {
            //如果焦点在最后一个元素，回车后添加新一行
            if ($(this).attr("name") == "price"
                && $(this).parents("tr").attr("data-id") == $("#table-data-right").find("tr:last").attr("data-id")) {

                //设置处方类别
                $.extend(expand_setting.param, {"search_recipeType": $("#treType").val()});
                $("#table-data-right").find("tbody").append(row);
                $("#table-data-right").find("tr:last").find("input[name=drgAndExaName]").grayExpandTable(expand_setting);

                $nbp.off("keydown");

                $nbp = $("#table-data-right input:text, #table-data-right select");
                var next = $nbp.index(this) + 1;
                $nbp.eq(next).focus();

                /**处方序号重新计算**/
                initTreNum();
                //重新绑定回车事件处理方法
                keydownEvent(row);
            } else {
                var next = $nbp.index(this) + 1;
                $nbp.eq(next).focus();
            }
        }
    });
}
//中药表格
function createCN(data) {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center" onclick="openTable(this)"><input type="checkbox" onclick="event.stopPropagation()" onchange="toggleFee(this)"><span>中药开方</span><i class="iconfont icon-xiayiye5-copy-copy arrow-rotate ml5"></i></h4>' +
        '<table class="table table-fixed table-hover text-center" style="display: table" data-rd=' + data[0].recipeId + '>' +
        '<thead><tr>' +
        '<td colspan="2">是否自费</td>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">药品名称</td>' +
        '<td colspan="2">单次剂量</td>' +
        '<td colspan="2">单位</td>' +
        '<td colspan="2">特殊用法</td>' +
        '<td colspan="2">单价（元）</td>' +
        '<td colspan="2">金额</td>' +
        '<td colspan="2">诊疗医生</td>' +
        '<td colspan="2">费用等级</td>' +
        ' </tr></thead>' +
        '<tbody>';
    for (var j = 0; j < data.length; j++) {
        html += '<tr data-id=' + data[j].id + '>' +
            '<td colspan="2"><input type="checkbox" onchange="selectRow(this)" class="select-single"></td>' +
            '<td colspan="2">' + data[j].catName + '</td>' +
            '<td colspan="5">' + data[j].drgName + '</td>' +
            '<td colspan="2">' + data[j].redQuantity + '</td>' +
            '<td colspan="2">' + data[j].drgPackingUnit + '</td>' +
            '<td colspan="2">' + data[j].modName + '</td>' +
            '<td colspan="2">' + data[j].redPrice + '</td>' +
            '<td colspan="2">' + data[j].redSumFee + '</td>' +
            '<td colspan="2">' + data[j].sffName + '</td>' +
            '<td colspan="2">丙</td>' +
            '</tr>';
        sumFee += data[j].redSumFee * data[0].rcpPosts;
    }
    html += '<tr>' +
        '<td colspan="2" style="border-right:none"><input type="checkbox" onchange="selectAll(this)" class="select-all"></td>' +
        '<td colspan="11" style="border-right:none" class="text-left">' +
        '<button class="btn btn-xs btn-white pull-left" onclick="setSelf(this)">设为自费</button>' +
        '<button class="btn btn-xs btn-white pull-left ml10" onclick="cancelSelf(this)">取消自费</button>' +
        '<span class="bold pull-left ml15">贴数：' + data[0].rcpPosts + '</span>' +
        '<span class="bold pull-left ml35">用法：煎服</span>' +
        '</td>' +
        '<td colspan="10">' +
        '<span class="bold pull-right fs-orange switch-on" style="display: none">该项不计入本次收费</span>' +
        '<span class="bold pull-right switch-off">合计金额：' + sumFee + '元</span>' +
        '<span class="bold pull-right mr20 switch-off">总计：' + data.length + '项</span>' +
        '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);


}
//西药表格
function createWt(data) {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center" onclick="openTable(this)"><input type="checkbox" onclick="event.stopPropagation()" onchange="toggleFee(this)"><span>西药开方</span><i class="iconfont icon-xiayiye5-copy-copy arrow-rotate ml5"></i></h4>' +
        '<table class="table table-fixed table-hover text-center" style="display: table" data-rd=' + data[0].recipeId + '>' +
        '<thead><tr>' +
        '<td colspan="2">是否自费</td>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">药品名称</td>' +
        '<td colspan="2">单位</td>' +
        '<td colspan="2">给药方式</td>' +
        '<td colspan="2">频次</td>' +
        '<td colspan="2">用药天数</td>' +
        '<td colspan="2">数量</td>' +
        '<td colspan="2">单价（元）</td>' +
        '<td colspan="2">金额</td>' +
        '<td colspan="2">诊疗医生</td>' +
        '<td colspan="2">费用等级</td>' +
        ' </tr></thead>' +
        '<tbody>';
    for (var j = 0; j < data.length; j++) {
        html += '<tr data-id=' + data[j].id + '>' +
            '<td colspan="2"><input type="checkbox" onchange="selectRow(this)" class="select-single"></td>' +
            '<td colspan="2">' + data[j].catName + '</td>' +
            '<td colspan="5">' + data[j].drgName + '</td>' +
            '<td colspan="2">' + data[j].redDoseUnit + '</td>' +
            '<td colspan="2">' + data[j].modName + '</td>' +
            '<td colspan="2">' + data[j].freName + '</td>' +
            '<td colspan="2">' + data[j].redUseDay + '</td>' +
            '<td colspan="2">' + data[j].redQuantity + '</td>' +
            '<td colspan="2">' + data[j].redPrice + '</td>' +
            '<td colspan="2">' + data[j].redSumFee + '</td>' +
            '<td colspan="2">' + data[j].sffName + '</td>' +
            '<td colspan="2">丙</td>' +
            '</tr>';
        sumFee += data[j].redSumFee;
    }
    html += '<tr>' +
        '<td colspan="2" style="border-right:none"><input type="checkbox" onchange="selectAll(this)" class="select-all"></td>' +
        '<td colspan="15" style="border-right:none" class="text-left">' +
        '<button class="btn btn-xs btn-white pull-left" onclick="setSelf(this)">设为自费</button>' +
        '<button class="btn btn-xs btn-white pull-left ml10" onclick="cancelSelf(this)">取消自费</button>' +
        '</td>' +
        '<td colspan="10">' +
        '<span class="bold pull-right fs-orange switch-on" style="display:none">该项不计入本次收费</span>' +
        '<span class="bold pull-right switch-off">合计金额：' + sumFee + '元</span>' +
        '<span class="bold pull-right mr20 switch-off">总计：' + data.length + '项</span>' +
        '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);
}
//检验检查表格
function createJJ(data, words) {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center" onclick="openTable(this)"><input type="checkbox" onclick="event.stopPropagation()" onchange="toggleFee(this)"><span>' + words + '</span><i class="iconfont icon-xiayiye5-copy-copy arrow-rotate ml5"></i></h4>' +
        '<table class="table table-fixed table-hover text-center" style="display: table" data-ed=' + data[0].examineId + '>' +
        '<thead><tr>' +
        '<td colspan="2">是否自费</td>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">项目名称</td>' +
        '<td colspan="2">送检科室</td>' +
        '<td colspan="2">单价（元）</td>' +
        '<td colspan="2">数量</td>' +
        '<td colspan="2">单位</td>' +
        '<td colspan="2">金额</td>' +
        '<td colspan="2">诊疗医生</td>' +
        '<td colspan="2">费用等级</td>' +
        ' </tr></thead>' +
        '<tbody>';
    for (var j = 0; j < data.length; j++) {
        html += '<tr data-id=' + data[j].id + '>' +
            '<td colspan="2"><input type="checkbox" onchange="selectRow(this)" class="select-single"></td>' +
            '<td colspan="2">' + data[j].billType + '</td>' +
            '<td colspan="5">' + data[j].itemName + '</td>' +
            '<td colspan="2">' + data[j].depNames + '</td>' +
            '<td colspan="2">' + data[j].exdPrice + '</td>' +
            '<td colspan="2">' + data[j].exdQuantity + '</td>' +
            '<td colspan="2">' + data[j].itemUnit + '</td>' +
            '<td colspan="2">' + data[j].exdSumPrice + '</td>' +
            '<td colspan="2">' + data[j].sffName + '</td>' +
            '<td colspan="2">' + data[j].catName + '</td>' +
            '</tr>';
        sumFee += data[j].exdSumPrice;
    }
    html += '<tr>' +
        '<td colspan="2" style="border-right:none"><input type="checkbox" onchange="selectAll(this)" class="select-all"></td>' +
        '<td colspan="11" style="border-right:none" class="text-left">' +
        '<button class="btn btn-xs btn-white pull-left" onclick="setSelf(this)">设为自费</button>' +
        '<button class="btn btn-xs btn-white pull-left ml10" onclick="cancelSelf(this)">取消自费</button>' +
        '</td>' +
        '<td colspan="10">' +
        '<span class="bold pull-right fs-orange switch-on" style="display:none">该项不计入本次收费</span>' +
        '<span class="bold pull-right switch-off">合计金额：' + sumFee + '元</span>' +
        '<span class="bold pull-right mr20 switch-off">总计：' + data.length + '项</span>' +
        '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);
}
//收费项表格
function createFee(data) {
    var html = '';
    var sumFee = 0;
    html += '<div class="row col-sm-12">' +
        '<div class="table-radius ">' +
        '<h4 class="text-center" onclick="openTable(this)"><input type="checkbox" onclick="event.stopPropagation()" onchange="toggleFee(this)"><span>收费项目开单</span><i class="iconfont icon-xiayiye5-copy-copy arrow-rotate ml5"></i></h4>' +
        '<table class="table table-fixed table-hover text-center" style="display: table" data-ed=' + data[0].examineId + '>' +
        '<thead><tr>' +
        '<td colspan="2">是否自费</td>' +
        '<td colspan="2">类型</td>' +
        '<td colspan="5">项目名称</td>' +
        '<td colspan="2">单价（元）</td>' +
        '<td colspan="2">数量</td>' +
        '<td colspan="2">单位</td>' +
        '<td colspan="2">金额</td>' +
        '<td colspan="2">诊疗医生</td>' +
        '<td colspan="2">费用等级</td>' +
        ' </tr></thead>' +
        '<tbody>';
    for (var j = 0; j < data.length; j++) {
        html += '<tr data-id=' + data[j].id + '>' +
            '<td colspan="2"><input type="checkbox" onchange="selectRow(this)" class="select-single"></td>' +
            '<td colspan="2">' + data[j].billType + '</td>' +
            '<td colspan="5">' + data[j].itemName + '</td>' +
            '<td colspan="2">' + data[j].exdPrice + '</td>' +
            '<td colspan="2">' + data[j].exdQuantity + '</td>' +
            '<td colspan="2">' + data[j].itemUnit + '</td>' +
            '<td colspan="2">' + data[j].exdSumPrice + '</td>' +
            '<td colspan="2">' + data[j].sffName + '</td>' +
            '<td colspan="2">' + data[j].catName + '</td>' +
            '</tr>';
        sumFee += data[j].exdSumPrice;
    }
    html += '<tr>' +
        '<td colspan="2" style="border-right:none"><input type="checkbox" onchange="selectAll(this)" class="select-all"></td>' +
        '<td colspan="8" style="border-right:none" class="text-left">' +
        '<button class="btn btn-xs btn-white pull-left" onclick="setSelf(this)">设为自费</button>' +
        '<button class="btn btn-xs btn-white pull-left ml10" onclick="cancelSelf(this)">取消自费</button>' +
        '</td>' +
        '<td colspan="11">' +
        '<span class="bold pull-right fs-orange switch-on" style="display:none">该项不计入本次收费</span>' +
        '<span class="bold pull-right switch-off">合计金额：' + sumFee + '元</span>' +
        '<span class="bold pull-right mr20 switch-off">总计：' + data.length + '项</span>' +
        '</td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>' +
        '</div>';
    $('#detail').append(html);
}
//详情收起展开
function openTable(el) {
    var $div = $(el).parent();
    arrowRotate($div);
    if ($div.has('table').length) {
        $div.find('table').slideToggle();
    }
}
//处方计费切换
function toggleFee(el) {
    var $table = $(el).parent('h4').siblings('table');
    var isChecked = $(el).prop('checked');
    if (isChecked) {
        $table.find('.switch-on').show();
        $table.find('.switch-off').hide();
    } else {
        $table.find('.switch-on').hide();
        $table.find('.switch-off').show();
    }
}
//箭头转换
function arrowRotate($div) {
    var $i = $div.find('i');
    if ($i.hasClass('arrow-rotate')) {
        $i.removeClass('arrow-rotate');
        $i.addClass('arrow-rotateRecover');
    } else {
        $i.removeClass('arrow-rotateRecover');
        $i.addClass('arrow-rotate');
    }

}
//选中单行
function selectRow(el) {
    var $tr = $(el).parents('tr');
    var isChecked = $(el).prop('checked');
    var checkedNum = $(el).parents('table').find('.select-single:checked').length;
    var singleNum = $(el).parents('table').find('.select-single').length;
    if (checkedNum === singleNum) {
        $(el).parents('table').find('tr:last input').prop('checked', true);
    }
    if (isChecked) {
        $tr.addClass('success');
    } else {
        $tr.removeClass('success');
        $(el).parents('table').find('tr:last input').prop('checked', false);
    }
}
//全选按钮
function selectAll(el) {
    var $table = $(el).parents('table');
    var isChecked = $(el).prop('checked');
    if (isChecked) {
        $table.find('.select-single').prop('checked', true).change();
    } else {
        $table.find('.select-single').prop('checked', false).change();
    }
}
//收费
var flag = false;
$('#collect').click(function () {
    if (flag) {
        return;
    }
    flag = true;
    var $tables = $('#detail').find('table');
    var recipeIds = [];
    var examineIds = [];
    // var notNomalMoney=JSON.stringify(getnotNomalMoney());
    // var notNomalMoney=getnotNomalMoney();
    // log4j.info(notNomalMoney);
    $.each($tables, function (index, table) {
        if ($(table).prev().find('input').prop('checked')) {
            return true;
        }
        if ($(table).data('rd')) {
            recipeIds.push($(table).data('rd'))
        }
        if ($(table).data('ed')) {
            examineIds.push($(table).data('ed'))
        }
    })
    //获取非处方单的钱
    var notNomalMoney = getnotNomalMoney();
    //获取处方和检查项目的钱
    var nomalMoney;
    ajaxNormalPost('/chg/charges_info/getNmomalMoney', {
        visiteId: getUserId(),
        chargeRecipeIds: recipeIds.join(','),
        chargeExamineIds: examineIds.join(',')
    }, function (res) {
        nomalMoney = res.data;
        if (nomalMoney.message.length > 0) {
            layer.alert(nomalMoney.message)
        } else {
            var sumMoney;
            log4j.info(notNomalMoney + "非处方价格");
            log4j.info(nomalMoney.sumMoney + "处方价格");
            sumMoney = parseFloat(notNomalMoney) + parseFloat(nomalMoney.sumMoney);
            storage.setItem("sumMoney", sumMoney);
            storage.setItem("patId", nomalMoney.patId);
            storage.setItem("patName", nomalMoney.patName);
            storage.setItem("natureId", nomalMoney.natureId);
            storage.setItem("patCardNum", nomalMoney.patCardNum);
            storage.setItem("feeId", nomalMoney.feeId);
            storage.setItem("hospitalId", nomalMoney.hospitalId);
            storage.setItem("currentYearPay", nomalMoney.currentYearPay);
            storage.setItem("calendarYearPay", nomalMoney.calendarYearPay);
            storage.setItem("overrunPay", nomalMoney.overrunPay);
            storage.setItem("cashPay", nomalMoney.cashPay);
            storage.setItem("fundPay", nomalMoney.fundPay);
            storage.setItem("notice", nomalMoney.notice);
            storage.setItem("inParm", nomalMoney.inParm);
            storage.setItem("outParm", nomalMoney.outParm);
            $('#modal').attr("method", "getMoney");
            $('#modal').load("getMoney.html");
            $('#modal').on('hidden.bs.modal	', function () {
            })
            $('#modal').modal({
                keyboard: true
            });
        }
        flag=false;
    });
})

//设为自费
function setSelf(el) {
    var $trs = $(el).parents('table tbody').find('tr:not(tr:last)');
    var id = []
    $.each($trs, function (index, tr) {
        if ($(tr).find('input').prop('checked')) {
            id.push($(tr).data('id'));
            $(tr).find('td:last').addClass('fs-orange');
        }
    })
    log4j.info(id);
}
//取消自费
function cancelSelf(el) {
    var $trs = $(el).parents('table tbody').find('tr:not(tr:last)');
    var id = []
    $.each($trs, function (index, tr) {
        if ($(tr).find('input').prop('checked')) {
            id.push($(tr).data('id'));
            $(tr).find('td:last').removeClass('fs-orange');
        }
    })
    log4j.info(id);
}